<template>
  <div class="product-item">
    <nut-form ref="formRef" :model-value="formData" :rules="rules">
      <nut-form-item prop="action">
        <div class="num">{{ num }}</div>
        <div class="action">
          <button :disabled="isDisMoveUp" @click="handleMove('up')">上移</button>
          <button :disabled="isDisMoveDown" @click="handleMove('down')">下移</button>
          <button @click="handleDel">删除</button>
        </div>
      </nut-form-item>

      <nut-form-item prop="name">
        <template #label> 商品名称<span class="red-star">*</span> </template>

        <nut-input
          class="nut-input-text"
          placeholder="请输入商品名称"
          type="text"
          v-model="formData.name"
          max-length="100"
          @blur="customBlurValidate('name')"
        />
      </nut-form-item>

      <nut-form-item label="商品描述" prop="desc">
        <div class="box" @click="handleRouteJump('desc')">
          <div class="desc-text" v-if="formData.desc">{{ formData.desc }}</div>
          <div class="ph" v-else>添加图片和描述</div>

          <img
            v-if="formData.imageList && formData.imageList.length > 0"
            class="camera camera-img"
            :src="commonStore.img_domain + formData.imageList[0]"
          />
          <img v-else class="camera" src="@/assets/addstart/introduce/introduce_camera.png" />
          <img class="arrow" src="@/assets/addstart/introduce/introduce_arrow.png" />
        </div>
      </nut-form-item>

      <nut-form-item prop="specs">
        <template #label> 规格<span class="red-star">*</span> </template>

        <div class="box" @click="handleRouteJump('specs')">
          <div class="desc-text" v-if="formData.specs">
            {{ formData.specs }}
          </div>
          <div class="ph" v-else>请添加规格信息</div>
          <img class="arrow" src="@/assets/addstart/introduce/introduce_arrow.png" />
        </div>
      </nut-form-item>

      <nut-form-item label="价格(￥)" prop="desc">
        <div class="box" @click="handleRouteJump('specs')">
          <div class="price" v-if="formData.price">{{ formData.price }}</div>
          <div class="ph" v-else>请填写价格</div>
        </div>
      </nut-form-item>

      <nut-form-item label="库存" prop="stock">
        <div class="box" @click="handleRouteJump('specs')">
          <div class="desc-text" v-if="formData.stock">
            {{ formData.stock }}
          </div>
          <div class="ph" v-else>无限</div>
          <img class="arrow" src="@/assets/addstart/introduce/introduce_arrow.png" />
        </div>
      </nut-form-item>

      <nut-form-item label="划线价(￥)" prop="crossedPrice">
        <input
          class="nut-input-text"
          placeholder="建议高于商品价格"
          type="text"
          v-model="formData.crossedPrice"
          @keyup="formData.crossedPrice = unsignFloat(formData.crossedPrice)"
          @blur="formData.crossedPrice = unsignFloat(formData.crossedPrice)"
        />
      </nut-form-item>

      <nut-form-item label="成本价(￥)" prop="costPrice">
        <div class="box" @click="handleRouteJump('specs')">
          <div class="desc-text" v-if="formData.costPrice">
            {{ formData.costPrice }}
          </div>
          <div class="ph" v-else>用于利润核算，仅团长可见</div>
          <img class="arrow" src="@/assets/addstart/introduce/introduce_arrow.png" />
        </div>
      </nut-form-item>
    </nut-form>

    <del-dialog ref="delDialogRef" @confirm="handleDialogConfirm"></del-dialog>
  </div>
</template>

<script lang="ts" setup>
  import DelDialog from "@/components/Dialog/index.vue"
  import useCommonStore from "@/store/common"
  import { ref, onActivated } from "vue"
  import { useRouter } from "vue-router"
  import { unsignFloat } from "@/utils/pub-use"
  // - props
  interface IProps {
    productDetail: any
    num: number
    isDisMoveUp: boolean
    isDisMoveDown: boolean
  }
  const props = defineProps<IProps>()

  // - router
  const router = useRouter()

  // - emits
  const emit = defineEmits(["delProduct", "move", "save"])

  // ------- store
  const commonStore = useCommonStore()

  // - data
  const routeMap: any = {
    desc: "/productdesc",
    specs: "/spec/specSet"
  }
  const delDialogRef = ref<InstanceType<typeof DelDialog>>()
  const formRef = ref<any>(null)
  const formData = ref<any>({
    id: props.productDetail.id,
    name: "",
    desc: "",
    specs: "",
    specData: {},
    price: "",
    stock: "",
    crossedPrice: "",
    costPrice: "",
    imageList: []
  })
  const rules = {
    name: [
      {
        required: true,
        message: "必须填写商品名称"
      }
    ]
  }

  // - methods
  const handleMove = (type: string) => {
    emit("move", { type, id: props.productDetail.id })
  }
  const handleDel = () => {
    delDialogRef.value?.openDialog()
  }
  const handleDialogConfirm = () => {
    emit("delProduct", props.productDetail.id)
  }
  const handleRouteJump = (path: string) => {
    router.push({
      path: routeMap[path],
      query: {
        id: props.productDetail.id
      }
    })
  }
  const customBlurValidate = (prop: string) => {
    formRef.value.validate(prop).then(({ valid, errors }: any) => {
      if (!valid) {
        console.log("error sumbit")
      }
    })
  }
  const submit = () => {
    return new Promise((resolve) => {
      formRef.value.validate().then(({ valid, errors }: any) => {
        if (valid) {
          resolve({ ...formData.value })
        } else {
          resolve(false)
        }
      })
    })
  }

  // - lifecycle
  // function init() {
  //   const localProductsItem = window.localStorage.getItem(`productsItem-${props.productDetail.id}`)
  //   localProductsItem && (formData.value = JSON.parse(localProductsItem))
  // }
  // init()
  // onBeforeUnmount(() => {
  //   window.localStorage.setItem(
  //     `productsItem-${props.productDetail.id}`,
  //     JSON.stringify(formData.value)
  //   )
  // })
  onActivated(() => {
    const localProductsDesc = window.localStorage.getItem(`productDesc-${props.productDetail.id}`)
    if (localProductsDesc) {
      const { desc, imageList } = JSON.parse(localProductsDesc)
      formData.value.desc = desc
      formData.value.imageList = imageList
    }

    const localSpecData1 = window.localStorage.getItem(`specData1-${props.productDetail.id}`)
    const localSpecData2 = window.localStorage.getItem(`specData2-${props.productDetail.id}`)
    if (localSpecData2 && localSpecData1) {
      const specData1 = JSON.parse(localSpecData1)
      const specData2 = JSON.parse(localSpecData2)

      formData.value.specData.specData1 = specData1
      formData.value.specData.specData2 = specData2

      // 规格
      let temStr = specData2.reduce((pre: any, nxt: any) => {
        return pre + "/" + nxt.name
      }, "")
      formData.value.specs = temStr.slice(1)

      // 价格、库存
      let maxPrice = -1
      let minPrice = 999999999999
      let stock = 0
      specData2.forEach((item: any) => {
        if (item.price > maxPrice) maxPrice = item.price * 1
        if (item.price < minPrice) minPrice = item.price * 1

        stock = stock + item.stok * 1
      })
      if (minPrice == maxPrice) {
        formData.value.price = minPrice
      } else {
        if (maxPrice == -1 && minPrice == 999999999999) {
          formData.value.price = ""
        } else {
          formData.value.price = minPrice + " - " + maxPrice
        }
      }
      formData.value.stock = stock

      // 成本价
      let maxBasePrice: any = -1
      let minBasePrice: any = 999999999999
      specData2.forEach((item: any) => {
        if (item.basePrice > maxBasePrice) maxBasePrice = item.basePrice * 1
        if (item.basePrice < minBasePrice) minBasePrice = item.basePrice * 1
      })
      if (minBasePrice == maxBasePrice) {
        formData.value.costPrice = minBasePrice
      } else {
        if (maxBasePrice == -1 && minBasePrice == 999999999999) {
          formData.value.costPrice = ""
        } else {
          formData.value.costPrice = minBasePrice + " - " + maxBasePrice
        }
      }
    }
  })

  // - expose
  defineExpose({ submit })
</script>

<style lang="scss" scoped>
  .product-item {
    width: 670px;
    border-radius: 20px;
    background: #f7f8f9;
    overflow: hidden;
    margin-bottom: 20px;

    .red-star {
      color: #ff0000;
    }
    .price {
      font-size: 28px;
      font-family: PingFang-SC-Regular, PingFang-SC;
      font-weight: 400;
      color: #f55726;
    }

    .num {
      position: absolute;
      left: 0;
      top: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      background: url("../../../../assets/addstart/introduce/introduce_num.png") no-repeat center
        center / 100% 100%;
      width: 56px;
      height: 40px;
      font-size: 30px;
      font-family: Roboto-Medium, Roboto;
      font-weight: 500;
      color: #40ae36;
    }
    .action {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      position: relative;
      width: 100%;
      height: 100%;

      button {
        background: none;
        width: 73px;
        height: 40px;
        border-radius: 6px;
        border: 1px solid #a7b3a5;
        font-size: 24px;
        font-family: PingFang-SC-Regular, PingFang-SC;
        font-weight: 400;
        color: #000000;
        margin-left: 20px;
      }

      button:disabled {
        opacity: 0.5;
      }
    }

    .box {
      position: relative;
      font-size: 28px;
      font-family: PingFang-SC-Regular, PingFang-SC;
      font-weight: 400;
      color: #000000;

      .desc-text {
        width: 326px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .ph {
        color: #757575;
      }

      .camera,
      .arrow {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
      }
      .camera {
        right: 56px;
        width: 64px;
      }
      .camera.camera-img {
        width: 64px;
        height: 64px;
      }
      .arrow {
        right: 20px;
        width: 26px;
      }
    }

    // 修改默认样式
    .nut-cell.nut-form-item.line {
      min-height: 96px;
      border-bottom: 1px solid #eeeeee;
      padding: 0 20px;
      align-items: center;

      :deep(.nut-input) {
        width: 100%;
        height: 100%;
        border: none;
        padding-left: 0;
        padding-right: 0;
        background: none;

        .input-text {
          width: 100%;
        }
      }
    }
    .item:last-of-type {
      border-bottom: none;
    }

    :deep(.nut-cell-group__warp) {
      margin: 0;
      font-size: 28px;
      font-family: PingFang-SC-Regular, PingFang-SC;
      font-weight: 400;
      color: #999999;

      .nut-cell {
        background: #f7f8f9;
      }

      .nut-form-item__label {
        width: 162px;
        color: #000000;
      }
    }
  }
</style>
